<template>
  <div class="app-container">
    <div class="home project">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        @submit.native.prevent
      >
        <el-row justify="space-between">
          <el-col :span="6" style="padding-top: 3px">
            <span style="font-size: 14px; font-weight: 600">供应商名称</span>
            <el-input
              v-model="queryParams.supplierName"
              placeholder="请输入供应商名称"
              style="width: 220px; margin-left: 20px"
              prefix-icon="search"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
          <el-col :span="6" style="text-align: left">
            <el-form-item style="text-align: left">
              <el-button
                style="background-color: #4c6ee2; color: white"
                size="small"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button size="small" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div
        class="status-filter"
        style="
          display: flex;
          justify-content: space-between;
          padding-bottom: 20px;
        "
      >
        <div></div>
        <div>
          <el-button
            type="primary"
            size="small"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['food:supplier:add']"
            >新增</el-button
          >
          <el-button
            type="success"
            size="small"
            plain
            icon="el-icon-edit"
            @click="handleBatchEdit"
            v-hasPermi="['food:supplier:edit']"
            >修改</el-button
          >
          <el-button
            type="info"
            size="small"
            plain
            icon="el-icon-upload2"
            @click="handleImport"
            >导入</el-button
          >
          <el-button
            type="warning"
            size="small"
            plain
            icon="el-icon-download"
            @click="handleExport"
            >导出</el-button
          >
          <el-button
            type="danger"
            size="small"
            plain
            icon="el-icon-delete-solid"
            @click="handleBatchDelete"
            >删除</el-button
          >
        </div>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        max-height="700"
        stripe
        class="table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" align="left" />
        <el-table-column
          prop="supplierCode"
          label="统一信用代码"
          align="left"
        />
        <el-table-column
          prop="supplierBankNumber"
          label="银行账号"
          align="left"
        />
        <el-table-column
          prop="supplierBank"
          label="开户行"
          align="left"
        ></el-table-column>
        <el-table-column
          prop="supplierInterBank"
          label="联行号"
          align="left"
        ></el-table-column>
        <el-table-column prop="supplierFee" label="手续费" align="left">
          <template slot-scope="scope">
            {{ scope.row.supplierFee > 0 ? scope.row.supplierFee + "%" : "" }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="资质图片" align="left">
              <template slot-scope="scope">
                <div v-if="scope.row.aptUrl"> -->
        <!-- <el-popover placement="right" trigger="click"> -->
        <!-- <div style="display: flex; flex-wrap: wrap; max-width: 400px;">
                      <div v-for="(url, index) in (scope.row.aptUrl.split(','))"
                       :key="index" style="margin: 5px;">
                        <el-image 
                          style="width: 30px; height: 30px;"
                          :src="url" 
                          :preview-src-list="scope.row.aptUrl.split(',')"
                          fit="cover">
                        </el-image>
                      </div>
                    </div> -->
        <!-- </div>
                <span v-else>-</span>
              </template>
            </el-table-column> -->
        <el-table-column label="资质文件" align="left" width="300">
          <template slot-scope="scope">
            <div
              v-if="scope.row.aptUrl && scope.row.aptUrl.length"
              style="display: flex; flex-wrap: wrap; gap: 10px"
            >
              <div
                v-for="(file, index) in parseFileList(scope.row.aptUrl)"
                :key="index"
              >
                <!-- 图片显示缩略图 -->
                <div v-if="isImage(file)" style="display: inline-block">
                  <el-image
                    style="
                      width: 30px;
                      height: 30px;
                      margin-right: 5px;
                      border-radius: 50%;
                    "
                    :src="file.url"
                    fit="cover"
                    :preview-src-list="getPreviewList(scope.row.aptUrl)"
                  >
                  </el-image>
                </div>
                <!-- 非图片显示文件链接 -->
                <div v-else style="display: inline-block">
                  <el-link
                    type="primary"
                    :href="file.url"
                    target="_blank"
                    style="margin-right: 10px"
                  >
                    <el-icon><Document /></el-icon>
                    {{ file.name || "下载文件" }}
                  </el-link>
                </div>
              </div>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="supplierSettlementMethod"
          label="结算方式"
          align="left"
        >
          <template slot-scope="scope">
            <div
              v-for="(item, index) in dict.type.food_settlement_method"
              :key="index"
            >
              {{
                item.value == scope.row.supplierSettlementMethod
                  ? item.label
                  : ""
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="备注"
          prop="remark"
          align="left"
        ></el-table-column>
        <el-table-column label="联系方式">
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color: #4c6ee2"
              @click="handleDelis(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="date"
          label="操作"
          class-name="small-padding fixed-width"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="edit"
              style="color: #4c6ee2"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['food:supplier:edit']"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="delete"
              style="color: #4c6ee2"
              v-hasPermi="['food:supplier:remove']"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right">
        <el-pagination
          style="margin-top: 32px"
          :current-page.sync="queryParams.pageNum"
          :page-size.sync="queryParams.pageSize"
          :background="background"
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加或修改部门对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="open"
      width="706px"
      center
    >
      <template #title>
        <div class="custom-dialog-title">
          <div
            style="
              display: flex;
              border-bottom: 1px solid rgba(0, 0, 0, 0.05);
              padding-bottom: 20px;
              padding-left: 30px;
            "
          >
            <div
              style="
                background-color: #4c6ee2;
                border-radius: 20px;
                width: 4px;
                margin-right: 8px;
                height: 20px;
                margin-top: 6.5px;
              "
            ></div>
            <span
              class="title-text"
              style="
                font-family: Source Han Sans;
                font-size: 20px;
                font-weight: 500;
                line-height: 31px;
                text-align: center;
                letter-spacing: normal;
                color: #3d3d3d;
              "
              >{{ title }}</span
            >
          </div>
        </div>
      </template>
      <div
        style="
          font-family: Source Han Sans;
          font-size: 20px;
          font-weight: 500;
          line-height: 31px;
          margin-left: 20px;
          display: flex;
          letter-spacing: normal;
          color: #3d3d3d;
        "
      >
        <img
          src="@/assets/images/updatesvn.svg"
          alt=""
          style="margin-top: 0px; padding-right: 4px"
        />
        基本信息
      </div>
      <el-form
        ref="deptRef"
        :model="form"
        :rules="rules"
        label-position="top"
        label-width="80px"
        class="dialogN"
        style="margin-left: 20px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="供应商名称"
              prop="supplierName"
              label-width="100px"
            >
              <el-input
                v-model="form.supplierName"
                style="width: 90%"
                placeholder="请输入供应商名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="统一信用代码"
              prop="supplierCode"
              label-width="120px"
            >
              <el-input
                v-model="form.supplierCode"
                style="width: 90%"
                placeholder="请输入统一信用代码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="银行账号" prop="supplierBankNumber">
              <el-input
                style="width: 90%"
                v-model="form.supplierBankNumber"
                placeholder="请输入银行账号"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系地址" prop="supplierAddress">
              <el-input
                style="width: 90%"
                v-model="form.supplierAddress"
                placeholder="请输入联系地址"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="开户行信息"
              label-width="100px"
              prop="supplierBank"
            >
              <el-input
                v-model="form.supplierBank"
                style="width: 90%"
                placeholder="请输入开户行信息"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联行号" prop="supplierInterBank">
              <el-input
                style="width: 90%"
                v-model="form.supplierInterBank"
                placeholder="请输入联行号"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商税费" prop="supplierFee">
              <el-input
                style="width: 90%"
                type="number"
                v-model="form.supplierFee"
                placeholder="请输入开票税点"
                @input="inputNumber"
              >
                <template slot="suffix">
                  <i
                    class="iconfont icon-baifenhao"
                    style="line-height: 40px"
                  ></i>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算方式" prop="supplierSettlementMethod">
              <el-select
                v-model="form.supplierSettlementMethod"
                placeholder="请选择"
                style="width: 90%"
              >
                <el-option
                  v-for="dict in dict.type.food_settlement_method"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                style="width: 95%; height: 70px !important"
                placeholder="请输入备注"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <div
          style="
            font-family: Source Han Sans;
            font-size: 20px;
            font-weight: 500;
            padding-top: 13px;
            line-height: 31px;
            display: flex;
            letter-spacing: normal;
            color: #3d3d3d;
          "
        >
          <img
            src="@/assets/images/updatesvn.svg"
            alt=""
            style="margin-top: 0px; padding-right: 4px"
          />
          联系人信息
        </div>

        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人1" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入联系人"
                maxlength="50"
                style="width: 90%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入联系方式"
                maxlength="50"
                style="width: 90%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人2" prop="name1">
              <el-input
                v-model="form.name1"
                placeholder="请输入联系人"
                maxlength="50"
                style="width: 90%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone1">
              <el-input
                v-model="form.phone1"
                placeholder="请输入联系方式"
                maxlength="50"
                style="width: 90%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人3" prop="name2">
              <el-input
                v-model="form.name2"
                placeholder="请输入联系人"
                maxlength="50"
                style="width: 90%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone2">
              <el-input
                v-model="form.phone2"
                placeholder="请输入联系方式"
                maxlength="50"
                style="width: 90%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上传供应商资质" prop="image">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="handleImageChange"
                :file-list="fileList"
                :before-upload="beforeUpload"
                :show-file-list="true"
                multiple
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="cancel"
          style="
            background-color: white;
            color: #4c6ee2;
            border: 1px solid #4c6ee2;
          "
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitForm"
          style="background-color: #4c6ee2; color: white"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 供应商详情对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="opens"
      width="706px"
      center
    >
      <template #title>
        <div class="custom-dialog-title">
          <div
            style="
              display: flex;
              border-bottom: 1px solid rgba(0, 0, 0, 0.05);
              padding-bottom: 20px;
              padding-left: 30px;
            "
          >
            <div
              style="
                background-color: #4c6ee2;
                border-radius: 20px;
                width: 4px;
                margin-right: 8px;
                height: 20px;
                margin-top: 6.5px;
              "
            ></div>
            <span
              class="title-text"
              style="
                font-family: Source Han Sans;
                font-size: 20px;
                font-weight: 500;
                line-height: 31px;
                text-align: center;
                letter-spacing: normal;
                color: #3d3d3d;
              "
              >详情</span
            >
          </div>
        </div>
      </template>

      <div
        style="
          font-family: Source Han Sans;
          font-size: 20px;
          font-weight: 500;
          line-height: 31px;
          margin-left: 20px;
          display: flex;
          letter-spacing: normal;
          color: #3d3d3d;
        "
      >
        <img
          src="@/assets/images/updatesvn.svg"
          alt=""
          style="padding-right: 4px"
        />
        基本信息
      </div>

      <div class="detail-content" style="margin-left: 20px">
        <el-row>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">供应商名称：</div>
              <div class="detail-value">{{ form.supplierName || "-" }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">统一信用代码：</div>
              <div class="detail-value">{{ form.supplierCode || "-" }}</div>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">银行账号：</div>
              <div class="detail-value">
                {{ form.supplierBankNumber || "-" }}
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联系地址：</div>
              <div class="detail-value">{{ form.supplierAddress || "-" }}</div>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">开户行信息：</div>
              <div class="detail-value">{{ form.supplierBank || "-" }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联行号：</div>
              <div class="detail-value">
                {{ form.supplierInterBank || "-" }}
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">开票税点：</div>
              <div class="detail-value">
                {{ form.supplierFee ? form.supplierFee + "%" : "-" }}
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">结算方式：</div>
              <div
                class="detail-value"
                v-if="
                  dict.type.food_settlement_method.filter(
                    (el) => el.value == form.supplierSettlementMethod
                  ).length > 0
                "
              >
                {{
                  dict.type.food_settlement_method.filter(
                    (el) => el.value == form.supplierSettlementMethod
                  )[0].label || "-"
                }}
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <div class="detail-item">
              <div class="detail-label">备注：</div>
              <div class="detail-value" style="width: 95%">
                {{ form.remark || "-" }}
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div
        style="
          font-family: Source Han Sans;
          margin-left: 20px;
          font-size: 20px;
          font-weight: 500;
          line-height: 31px;
          display: flex;
          letter-spacing: normal;
          color: #3d3d3d;
        "
      >
        <img
          src="@/assets/images/updatesvn.svg"
          alt=""
          style="margin-top: 0px; padding-right: 4px"
        />
        联系人信息
      </div>

      <div class="detail-content" style="margin-left: 20px">
        <el-row>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联系人1：</div>
              <div class="detail-value">{{ form.name || "-" }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联系方式：</div>
              <div class="detail-value">{{ form.phone || "-" }}</div>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联系人2：</div>
              <div class="detail-value">{{ form.name1 || "-" }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联系方式：</div>
              <div class="detail-value">{{ form.phone1 || "-" }}</div>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联系人3：</div>
              <div class="detail-value">{{ form.name2 || "-" }}</div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="detail-item">
              <div class="detail-label">联系方式：</div>
              <div class="detail-value">{{ form.phone2 || "-" }}</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <div
        style="
          font-family: Source Han Sans;
          font-size: 20px;
          font-weight: 500;
          margin-left: 20px;
          line-height: 31px;
          display: flex;
          letter-spacing: normal;
          color: #3d3d3d;
        "
      >
        <img
          src="@/assets/images/updatesvn.svg"
          alt=""
          style="margin-top: 0px; padding-right: 4px"
        />
        供应商资质
      </div>

      <div style="margin-left: 20px; padding-bottom: 20px; margin-top: 10px">
        <el-image
          v-for="(item, index) in fileList"
          :key="index"
          :src="item.url"
          :preview-src-list="fileList.map((i) => i.url)"
          style="width: 100px; height: 100px; margin-right: 10px"
        ></el-image>
        <div v-if="fileList.length === 0" style="color: #999">暂无资质文件</div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          @click="opens = false"
          style="
            background-color: white;
            color: #4c6ee2;
            border: 1px solid #4c6ee2;
          "
          >关 闭</el-button
        >
      </div>
    </el-dialog>
    <supplier-info
      @dialogClose="dialogClose"
      :formData="formData"
      v-if="centerDialogVisible"
      :centerDialogVisible.sync="centerDialogVisible"
    ></supplier-info>

    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <!-- <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据 -->
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button
          @click="submitFileForm"
          style="background-color: #4c6ee2; color: white"
          >确 定</el-button
        >
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import supplierInfo from "@/components/supplierInfo/index.vue";
import {
  listData,
  getData,
  addData,
  updateData,
  delData,
} from "@/api/customer/supplier";
import { uploading, getList as getlists } from "@/api/cuisine";
import { getToken } from "@/utils/auth";

export default {
  components: {
    supplierInfo,
  },
  dicts: ["food_settlement_method"],
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierName: undefined,
      },
      opens: false,
      background: true,
      multipleSelection: [],
      open: false,
      title: "",
      total: 0,
      tableData: [],
      loading: true,
      formData: {},
      centerDialogVisible: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/food/supplier/importData",
      },
      form: {
        aptUrl: "", // 存储图片URL，多个用逗号分隔
      },
      rules: {
        supplierName: [
          { required: true, message: "平台名称不能为空", trigger: "blur" },
        ],
      },
      fileList: [], // 上传文件列表
      erp_bank: [],
      food_settlement_method: [],
    };
  },
  created() {
    this.getDicts();
    this.getList();
  },
  methods: {
    handleImport() {
      this.upload.title = "供应商导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const link = document.createElement("a");
      link.href = "/供应商导入模板.xlsx";
      link.download = "供应商导入模板.xlsx";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    parseFileList(aptUrl) {
      try {
        if (!aptUrl) return [];

        if (typeof aptUrl === "string") {
          try {
            const parsed = JSON.parse(aptUrl);
            return Array.isArray(parsed) ? parsed : [];
          } catch (e) {
            return aptUrl
              .split(",")
              .filter((url) => url.trim())
              .map((url) => ({
                url: url.trim(),
                name: url.split("/").pop() || "文件",
              }));
          }
        }

        return Array.isArray(aptUrl) ? aptUrl : [];
      } catch (e) {
        console.error("解析文件列表失败:", e);
        return [];
      }
    },

    // 判断是否是图片
    isImage(file) {
      if (!file || !file.url) return false;
      const imageExtensions = [
        ".png",
        ".jpg",
        ".jpeg",
        ".gif",
        ".bmp",
        ".webp",
      ];
      const url = file.url.toLowerCase();
      return imageExtensions.some((ext) => url.includes(ext));
    },

    // 获取预览列表（仅图片）
    getPreviewList(aptUrl) {
      return this.parseFileList(aptUrl)
        .filter((file) => this.isImage(file))
        .map((file) => file.url);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "food/supplier/export",
        {
          ...this.queryParams,
        },
        `供应商导出${new Date().toISOString().slice(0, 10)}.xlsx`
      );
    },
    beforeUpload(file) {
      const isImage = file.type.includes("image/");
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error("只能上传图片文件！");
        return false;
      }
      if (!isLt5M) {
        this.$message.error("图片大小不能超过5MB！");
        return false;
      }

      return true;
    },

    handleRemove(file, fileList) {
      this.fileList = fileList;
      // 更新form.aptUrl，移除被删除的图片URL
      const urls = this.fileList.map((item) => item.url || item.response?.data);
      console.log(this.fileList);
      this.form.aptUrl = JSON.stringify(this.fileList);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },

    async handleImageChange(file, fileList) {
      this.fileList = fileList;
      if (file.status === "ready") {
        try {
          const formData = new FormData();
          formData.append("file", file.raw);

          console.log(file);
          const response = await uploading(formData);

          if (response.code === 200) {
            // 更新当前文件的上传状态和URL
            const index = this.fileList.findIndex(
              (item) => item.uid === file.uid
            );
            if (index !== -1) {
              this.$set(this.fileList[index], "url", response.data);
              this.$set(this.fileList[index], "name", file.name);
              this.$set(this.fileList[index], "status", "success");
            }

            // 更新form.aptUrl，包含所有图片URL
            const urls = this.fileList
              .map((item) => item.url || item.response?.data)
              .filter((url) => url);
            console.log(this.fileList);
            console.log(urls);
            // this.form.aptUrl = urls.join(',');
            this.form.aptUrl = JSON.stringify(this.fileList);

            this.$message.success("图片上传成功");
          } else {
            throw new Error(response.data || "上传失败");
          }
        } catch (error) {
          console.error("上传失败:", error);
          this.$message.error(error.message);
          // 移除上传失败的文件
          this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
        }
      }
    },

    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }
      const names = this.multipleSelection
        .map((item) => item.supplierName)
        .join("、");
      this.$confirm(
        `确定删除选中的${this.multipleSelection.length}条记录吗?【${names}】`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const ids = this.multipleSelection.map((item) => item.id).join(",");
            await delData(ids);
            this.$message.success("批量删除成功");
            this.getList();
          } catch (error) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleBatchEdit() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }
      if (this.multipleSelection.length > 1) {
        this.$message.warning("暂不支持批量编辑");
        return;
      }
      this.handleUpdate(this.multipleSelection[0]);
    },
    getDicts() {
      // this.getDict('erp_bank').then(response => {
      //   this.erp_bank = response.data
      // })
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    inputNumber(val) {
      if (val >= 100) {
        this.form.supplierFee = 100;
      }
    },
    resetQuery() {
      this.queryParams.supplierName = "";
      this.$refs.queryRef.resetFields();
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    dialogClose() {
      this.centerDialogVisible = false;
    },
    getList() {
      this.loading = true;
      this.tableData = [];
      listData(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = Number(response.total);
        this.loading = false;
      });
    },
    handleAdd() {
      this.form = {
        aptUrl: "",
      };
      this.fileList = [];
      this.open = true;
      this.title = "新增供应商";
    },
    submitForm() {
      this.$refs.deptRef.validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateData({
              ...this.form,
              supplierContacts1:
                this.form.name && this.form.phone
                  ? this.form.name + "-&&-" + this.form.phone
                  : "",
              supplierContacts2:
                this.form.name1 && this.form.phone1
                  ? this.form.name1 + "-&&-" + this.form.phone1
                  : "",
              supplierContacts3:
                this.form.name2 && this.form.phone2
                  ? this.form.name2 + "-&&-" + this.form.phone2
                  : "",
            }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData({
              ...this.form,
              supplierContacts1:
                this.form.name && this.form.phone
                  ? this.form.name + "-&&-" + this.form.phone
                  : "",
              supplierContacts2:
                this.form.name1 && this.form.phone1
                  ? this.form.name1 + "-&&-" + this.form.phone1
                  : "",
              supplierContacts3:
                this.form.name2 && this.form.phone2
                  ? this.form.name2 + "-&&-" + this.form.phone2
                  : "",
            }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleUpdate(row) {
      if (row.supplierContacts1) {
        this.$set(row, "name", row.supplierContacts1.split("-&&-")[0]);
        this.$set(row, "phone", row.supplierContacts1.split("-&&-")[1]);
      }
      if (row.supplierContacts2) {
        this.$set(row, "name1", row.supplierContacts2.split("-&&-")[0]);
        this.$set(row, "phone1", row.supplierContacts2.split("-&&-")[1]);
      }
      if (row.supplierContacts3) {
        this.$set(row, "name2", row.supplierContacts3.split("-&&-")[0]);
        this.$set(row, "phone2", row.supplierContacts3.split("-&&-")[1]);
      }
      this.form = JSON.parse(JSON.stringify(row));

      // 初始化图片列表
      this.fileList = [];
      if (this.form.aptUrl) {
        const urls = JSON.parse(this.form.aptUrl);
        urls.forEach((url) => {
          if (url) {
            this.fileList.push(url);
          }
        });
      }

      this.title = "编辑供应商";
      this.open = true;
    },
    handleDelete(row) {
      this.$confirm(
        '是否确认删除供应商名称为"' + row.supplierName + '"的数据项？',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          return delData(row.id);
        })
        .then(() => {
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
    handleDelis(row) {
      this.form = row;
      this.opens = true;
    },
    getDict(dictType) {
      return new Promise((resolve, reject) => {
        this.$store
          .dispatch("GetDict", dictType)
          .then((response) => {
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.detail-content {
  padding: 10px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 18px;
  line-height: 32px;
}

.detail-label {
  width: 120px;
  font-weight: bold;
  color: #606266;
  text-align: right;
  padding-right: 12px;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}
::v-deep .el-dialog {
  border-radius: 15px;
}
::v-deep .el-dialog__headerbtn .el-dialog__close {
  font-size: 25px;
}
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
::v-deep input[type="number"] {
  line-height: 1;
  -moz-appearance: textfield !important;
}

.app-container {
  padding: 20px;
  color: #333333;
}

::v-deep .el-dialog__body {
  padding-top: 5px;
}
::v-deep .el-input--medium .el-input__inner {
  height: 32px;
  line-height: 32px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}
::v-deep .el-form-item {
  margin-bottom: 10px;
}

::v-deep .dialogN .el-input--medium .el-input__inner {
  height: 42px;
  line-height: 42px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0);
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.2);
}
</style>
